<template>
    <div class="verbal_trick_container">
        <Grouping ref="GroupingRef" :type="groupIdtwo" :group-id="group_id" :auth-code="authCode" @submit="changeGroup">
            <el-tabs v-model="strTabIndex" class="tabs_box" @tab-change="chooseTabIndex">
                <el-tab-pane v-auth="'MY_VERBAL_TRICK'" label="我的话术" :name="1" />
                <el-tab-pane v-auth="'FIRM_VERBAL_TRICK'" label="企业话术" :name="2" />
            </el-tabs>
        </Grouping>
        <div class="verbal_trick_main">
            <ZwSearchForm ref="searchForm" row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                tab-h="initial"
                :option="tableOption"
                :row-key="getRowKey"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                @select-all="onSelectAll"
                @select="onSelect">
                <template #headerOperate>
                    <el-button
                        v-for="i in btns"
                        :key="i.id"
                        :disabled="i.isEdit"
                        :type="i.type == 'new' ? 'primary' : ''"
                        @click="verbalTrick_btn(i.type)">
                        {{ i.text }}
                    </el-button>
                </template>
            </ZwTable>
        </div>
    </div>
    <Dialog :app-dialog="appDialog">
        <div class="title" style="padding: 56px 0">确定删除所选内容吗？</div>
    </Dialog>
    <WordArt ref="WordArtRef" :type="groupIdtwo" @submit="initList" />
    <Drawer ref="ZwDrawer">
        <div class="phone_box">
            <PhonePreview
                ref="phonePreviewRef"
                :input-content-data="inputContentData"
                :material-content-data="materialContentData" />
        </div>
    </Drawer>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'CONTENT_HIHG_MATERIAL_VERBAL_TRICK' });
</script>

<script lang="tsx" setup>
import { ref, reactive, onMounted, onActivated, watch, nextTick } from 'vue';
// import Grouping from './Grouping.vue'
import Grouping from '@/components/ZWGroup.vue';
import { useStore } from '@/store';
import { useRoute } from 'vue-router';
import router from '@/router';
import { getSetionId, getVideoImage } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import { dividerProps, ElButton, ElMessage, ElPopover } from 'element-plus';
import { getCreateList } from '@/api/common';
import { verbalTricks, expSeep, batchOrDel, preview } from '@/api/highMaterial/verbalTrick';

import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import Dialog from '@/components/Dialog.vue';
import WordArt from '@/components/WordArt.vue';
import Drawer from '@/components/ZWDrawer.vue';
import Friend from './Friend.vue';
import PhonePreview from '@/components/zw/phonePreview/welcomePhonePreview/materialPreview/index.vue';
import { initMaterialData } from '@/utils/utils';

const phonePreviewRef = ref<HTMLElement | null>();
const inputContentData = ref<string>(''); //  用户存放回显数据  欢迎语输入框
const materialContentData = ref<Array<any>>([]);

const store = useStore();
const route = useRoute();

// 默认选中的分组类型（个人/企业） ==> 新增完成后
const { group_type } = route.params;

const GroupingRef = ref();
const WordArtRef = ref();
const ZwDrawer = ref(null);
const searchForm = ref();
const tableRef = ref();
const titleText = ref('');
const groupIdtwo = ref(24);
const strTabIndex = ref(1);
const drawer = ref(false);
const delArr = ref([]);
const singleArr = ref<any>([]); // 单个删除数组
const FriendDetail = ref([]);
const group_id = ref<number | string>('all');
const single = ref(false); // 是否是单个删除

const btns = reactive([
    { id: 1, text: '批量删除', type: 'del', isEdit: true },
    // { id: 2, text: '导入话术', type: 'export' },
    { id: 3, text: '新建话术', type: 'new' }
]);
const tableBtns = reactive([
    { id: 1, text: '编辑' },
    { id: 2, text: '预览' },
    { id: 3, text: '删除' }
]);
// 列表参数
const defaultParams = reactive({
    title: '', // 话术标题
    // speechcraft_type: backId.value ? backId.value : 1, // 话术类型: 1-个人话术; 2-企业话术
    speechcraft_type: 1, // 话术类型: 1-个人话术; 2-企业话术
    group_id: group_id.value || 0, // 分组 id
    created_uid: [], // 创建人数组
    created_time: [] // 创建时间
});
// 分组权限code码
const authCode = {
    add: 'VT_ADD_SUBGROUP',
    edit: 'VT_EDIT_SUBGROUP',
    del: 'VT_DEL_SUBGROUP'
};
const currentParams = ref<any>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = ref([
    {
        label: '话术搜索',
        name: 'title',
        value: '',
        type: 'input',
        placeholder: '请输入话术标题进行搜索'
    },
    {
        label: '创建时间',
        name: 'created_time',
        value: [],
        type: 'datePicker',
        datePickerType: 'daterange',
        datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间'
    }
]);
// table 配置
const tableOption = ref([
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'title',
        label: '标题',
        width: 200
    },
    {
        prop: 'content_num',
        label: '话术内容',
        width: 120,
        render({ row, column, index }) {
            return (
                <div>
                    <span>{+row.attachment_num != 0 ? `${row.attachment_num} 条` : '--'}</span>
                </div>
            );
        }
    },
    {
        prop: 'desc',
        label: '描述',
        showOverflowTooltip: true,
        width: 280
    },
    {
        prop: 'send_num',
        label: '发送次数',
        width: 100
    },
    {
        prop: 'group_name',
        label: '所属分组',
        width: 120
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 200
    },
    {
        prop: 'operate',
        label: '操作',
        width: 210,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row, column, index }) {
            return tableBtns.map((item: any, index: number) => {
                return (
                    <ElButton size="small" onClick={() => tableBtn(row, item.id)}>
                        {item.text}
                    </ElButton>
                );
            });
        }
    }
]);

const getRowKey = (row: any) => {
    return row.id;
};

const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
// 调用列表接口
const fetchApi = () => {
    getTableH();
    return verbalTricks;
};
// 查询
const search = (data: any) => {
    tableRef.value.clearSelection();
    currentParams.value = {
        ...deepCopy(defaultParams),
        ...data,
        group_id: group_id.value,
        speechcraft_type: strTabIndex.value
    };
    state.searchParams = deepCopy(currentParams.value);
};
// 重置
const reset = (v?: any) => {
    tableRef.value.clearSelection();
    currentParams.value = {
        ...deepCopy(defaultParams),
        group_id: group_id.value,
        speechcraft_type: strTabIndex.value
    };
    state.searchParams = deepCopy(currentParams.value);
};
// 操作按钮
const verbalTrick_btn = (type: string) => {
    switch (type) {
        case 'del':
            titleText.value = '批量删除';
            appDialog.visible = true;
            break;
        case 'export':
            WordArtRef.value.isShowTag = false;
            WordArtRef.value.appDialog.title = '导入话术';
            WordArtRef.value.wordVisible = true;
            WordArtRef.value.apiText = '/scrm-api/console/media/content/speechcraft/template';
            store.dispatch('content/isNewWord', false);
            break;
        case 'new':
            router.push({
                path: '/content/highMaterial/verbalTrick/create',
                query: {
                    group_id: group_id.value === 'all' ? 0 : group_id.value,
                    type: 'new',
                    seepType: defaultParams.speechcraft_type,
                    groupType: +strTabIndex.value == 2 ? 25 : 24
                }
            });
            break;
    }
};
// 全选
const onSelectAll = (selection: any) => {
    delArr.value = getSetionId('id', selection);
    btns[0].isEdit = selection.length ? false : true;
};
// 单选
const onSelect = (selection: any) => {
    delArr.value = getSetionId('id', selection);
    btns[0].isEdit = selection.length ? false : true;
};

// 控制 drawer
const drawerFn = (is: boolean, row: string) => {
    ZwDrawer.value.title = row.title;
    preview({ speechcraft_id: row.id }).then((res: any) => {
        // getPhoneData(res.speechcraft_attachment, res.content)
        inputContentData.value = res.welcome_info.welcome_text;
        materialContentData.value = initMaterialData(res.welcome_info.welcome_material);
        ZwDrawer.value.drawer = is;
    });
    ZwDrawer.value.isShow = false;
};
// table 按钮
const tableBtn = (row: any, n: number) => {
    switch (n) {
        case 1:
            router.push({
                path: '/content/highMaterial/verbalTrick/create',
                query: {
                    id: row.id,
                    type: 'edit',
                    seepType: defaultParams.speechcraft_type,
                    groupType: +strTabIndex.value == 2 ? 25 : 24
                }
            });
            break;
        case 2:
            drawerFn(true, row);
            break;
        case 3:
            titleText.value = '删除提示';
            appDialog.visible = true;
            single.value = true;
            singleArr.value = [row.id];
    }
};
// 选择分组
const changeGroup = (val: any) => {
    store.commit('user/setApiList', [
        '/scrm-api/console/tenant/group/getLists',
        '/scrm-api/console/media/content/speechcraft/list'
    ]);
    tableRef.value.clearSelection();
    if (val.id === group_id.value) {
        GroupingRef.value.getGroup();
    } else {
        group_id.value = val.id;
    }
    currentParams.value = {
        ...deepCopy(defaultParams),
        ...currentParams.value,
        group_id: group_id.value,
        speechcraft_type: strTabIndex.value
    };
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
};
const chooseTabIndex = () => {
    store.commit('user/setApiList', [
        '/scrm-api/console/tenant/group/getLists',
        '/scrm-api/console/media/content/speechcraft/list'
    ]);
    tableRef.value.clearSelection();
    searchForm.value.reset();
    defaultParams.group_id = 'all';
    const type = +strTabIndex.value == 2 ? 25 : 24;
    groupIdtwo.value = type;
    defaultParams.speechcraft_type = +strTabIndex.value;
    state.searchParams = deepCopy(defaultParams);
    // GroupingRef.value.toggleGroupTab(type, 'all');
};
// 取消
const cancelHandel = () => {
    appDialog.visible = false;
    single.value = false;
};
const submitHandel = () => {
    store.commit('user/setApiList', [
        '/scrm-api/console/media/content/speechcraft/batch-del',
        '/scrm-api/console/tenant/group/getLists',
        '/scrm-api/console/media/content/speechcraft/list'
    ]);
    const arr = single.value ? singleArr.value : delArr.value;
    batchOrDel({ speechcraft_ids: arr }).then(async (res: any) => {
        tableRef.value.clearSelection();
        ElMessage.success('删除成功！');
        delArr.value = [];
        await GroupingRef.value.getGroup(groupIdtwo.value);
        currentParams.value = {
            ...deepCopy(defaultParams),
            ...currentParams.value,
            group_id: group_id.value,
            speechcraft_type: strTabIndex.value
        };
        state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
        btns[0].isEdit = true;
        cancelHandel();
    });
};
// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: titleText,
    width: '30%',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});
const initList = (val?: any) => {
    const formData = new FormData();
    formData.append('speechcraft_import', val);
    formData.append(`speechcraft_type`, +strTabIndex.value ? '2' : '1');
    expSeep(formData).then(async (res: any) => {
        WordArtRef.value.wordVisible = false;
        state.searchParams = deepCopy(defaultParams);
        await GroupingRef.value.getGroup(groupIdtwo.value);
        ElMessage.success('导入话术成功');
    });
};
onMounted(async () => {
    store.commit('user/setApiList', [
        '/scrm-api/console/tenant/group/getLists',
        '/scrm-api/console/media/content/speechcraft/list'
    ]);
    // await GroupingRef.value.getGroup(groupIdtwo.value);

    // 设置选中的分组标签（没有回调事件）
    // let groupId = Number(route.params?.group_id)
    // if (groupId) {
    //   GroupingRef.value.setCurrentSelectId({ id: groupId })
    // }
});

onActivated(async (val: any) => {
    store.commit('user/setApiList', [
        '/scrm-api/console/tenant/group/getLists',
        '/scrm-api/console/media/content/speechcraft/list'
    ]);
    if (route.query?.group_id) {
        tableRef.value.clearSelection();
        searchForm.value.reset();
        groupIdtwo.value = +strTabIndex.value == 2 ? 25 : 24;
        defaultParams.speechcraft_type = +strTabIndex.value;
        if (group_id.value == route.query?.group_id) {
            GroupingRef.value.changeGroup({ id: Number(route.query?.group_id) });
        } else {
            group_id.value = Number(route.query?.group_id);
        }
        // group_id.value = Number(route.query?.group_id);
        defaultParams.group_id = Number(route.query?.group_id);
        tableRef.value.clearSelection();
        state.searchParams.group_id = Number(route.query?.group_id);
        state.searchParams = deepCopy(defaultParams);
        // 这里是处理从新增页面携带group_type参数对应tabs默认选中异常的问题
        strTabIndex.value = Number(route.query?.group_type) || 1;
        // await GroupingRef.value.getGroup(groupIdtwo.value);
        // GroupingRef.value.changeGroup({ id: Number(route.query?.group_id) });
        // 这里是处理当前选中不正确的问题
        GroupingRef.value.setCurrentSelectId({ id: group_id.value });
        router.push({ query: {} });
    } else {
        await GroupingRef.value.getGroup(groupIdtwo.value);
    }
    tableRef.value.clearSelection();
    currentParams.value = {
        ...deepCopy(defaultParams),
        ...currentParams.value,
        group_id: group_id.value,
        speechcraft_type: strTabIndex.value
    };
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});

watch(
    () => strTabIndex.value,
    val => {
        if (+strTabIndex.value == 1 && searchOption.value.length > 2) {
            searchOption.value.splice(1, 1);
            tableOption.value.splice(6, 1);
        } else if (+strTabIndex.value == 2 && searchOption.value.length == 2) {
            const p = {
                label: '创建人',
                name: 'created_uid',
                value: [],
                multiple: true,
                type: 'select',
                filterable: true,
                placeholder: '请选择创建人',
                fetchOptionApi: () => {
                    return new Promise(resolve => {
                        getCreateList({}).then((res: any) => {
                            const targetArr = res.map((item: any) => {
                                item.name = `${item.name}  (${item.phone})`;
                                return item;
                            });
                            resolve(targetArr);
                        });
                    });
                },
                formatOption: (v: any) => ({
                    label: v.name,
                    value: v.id
                })
            };
            const p2 = {
                prop: 'created_name',
                label: '创建人',
                width: 120
            };
            searchOption.value.splice(1, 0, p);
            tableOption.value.splice(6, 0, p2);
        }
    },
    { deep: true, immediate: true }
);
</script>

<style lang="scss" src="./style.scss" scoped></style>
